"""Convert Beaker XML to KCIDB test plan."""
import argparse
import os
import pathlib
import sys
import xml.etree.ElementTree as ET

from cki_lib import misc
from cki_lib.kcidb.file import KCIDBFile
import sentry_sdk


def get_param(task, key):
    """Return value for given key param."""
    for param in task.iter('param'):
        if param.get('name') == key:
            return param.get('value')
    return None


def is_task_a_cki_test(task):
    """
    Identify when a task must be considered as a CKI TEST.

    We're introduced a new parameter "CKI_IS_TEST" with boolean
    value, in the past, we used "CKI_ID" paramater.

    In the future all tasks will have CKI_ID parameter
    """
    # New logic
    cki_is_test = get_param(task, 'CKI_IS_TEST')
    if cki_is_test is not None:
        return misc.strtobool(cki_is_test)
    # Old logic
    return get_param(task, 'CKI_ID') is not None


def xml_to_kcidb(beaker_xml_path, build_id, test_prefix):
    """Extract list of KCDIB test from beaker xml."""
    content = pathlib.Path(beaker_xml_path).read_bytes()
    root = ET.fromstring(content)
    tests = []

    for recipeset in root.iter('recipe'):
        for task in recipeset.iter('task'):
            if not is_task_a_cki_test(task):
                continue

            tests.append(
                {
                    'id': f'{build_id}_{test_prefix}_{get_param(task, "CKI_ID")}',
                    'origin': 'redhat',
                    'build_id': build_id,
                    'comment': get_param(task, 'CKI_NAME'),
                    'path': get_param(task, 'CKI_UNIVERSAL_ID'),
                    'waived': misc.strtobool(get_param(task, 'CKI_WAIVED')),
                }
            )

    return tests


def parse_args(argv):
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description='Convert Beaker XML to KCIDB.'
    )

    parser.add_argument(
        '--beaker-xml', default=os.environ.get('BEAKER_TEMPLATE_PATH'), type=str,
        help='A path to the Beaker XML file.',
    )

    parser.add_argument(
        '--kcidb-file', default=os.environ.get('KCIDB_DUMPFILE_NAME'), type=str,
        help='A path to the Beaker XML file.',
    )

    parser.add_argument(
        '--build-id', default=os.environ.get('KCIDB_BUILD_ID'), type=str,
        help='KCIDB Build ID.',
    )

    parser.add_argument(
        '--test-prefix', default=os.environ.get('KCIDB_TEST_PREFIX', 'upt'), type=str,
        help='KCIDB Test prefix.',
    )

    return parser.parse_args(argv)


def main(argv):
    """Generate test plan from Beaker XML."""
    args = parse_args(argv)
    kcidb_file = KCIDBFile(args.kcidb_file)

    for test in xml_to_kcidb(args.beaker_xml, args.build_id, args.test_prefix):
        kcidb_file.set_test(test['id'], test)

    kcidb_file.save()


if __name__ == '__main__':
    misc.sentry_init(sentry_sdk)
    main(sys.argv[1:])
